package com.yonyou.brigade.third_parties.didi.controller;

import com.yonyou.brigade.basic_init.enums.ChannelEnum;
import com.yonyou.brigade.basic_init.model.BriChannel;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.brigade.third_parties.didi.model.DiDiConfig;
import com.yonyou.brigade.third_parties.didi.service.IDiDiCompanyService;
import com.yonyou.brigade.third_parties.didi.service.IDiDiOrderService;
import com.yonyou.brigade.third_parties.didi.service.IDiDiUserService;
import com.yonyou.ybzboot.starter.common.result.BasicResult;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/thirdparties/didi")
public class DiDiController {

    @Autowired
    @Qualifier("briChannelServiceImpl")
    private IBriChannelService briChannelService;

    @Autowired
    @Qualifier("diDiUserServiceImpl")
    private IDiDiUserService diDiUserService;

    @Autowired
    @Qualifier("diDiOrderServiceImpl")
    private IDiDiOrderService diDiOrderService;

    @Autowired
    @Qualifier("diDiCompanyServiceImpl")
    private IDiDiCompanyService diDiCompanyService;

    @Value("${didi.authIndex}")
    private String authIndex;


    /**
     * 同步用户
     *
     * @param params <code>{"tenant":"zrexrqw8","org":"uvdfsjdflldaspdpiibnzlldasd"}</code>
     * @return <code>{"code":"0","message":"用户同步成功！"+erroInfo.toString()}</code>
     */
    @RequestMapping(value = "/asyuser", method = RequestMethod.POST)
    public @ResponseBody
    Map asyDiDiUsers(@RequestBody Map params) {
        String tenant = params.get("tenant").toString();
        Map result = diDiUserService.saveUsers(tenant);
        return result;
    }

    @RequestMapping(value = "/orders", method = RequestMethod.POST)
    public @ResponseBody
    Map getDiDiOrders(@RequestBody Map params) {
        String tenant = (String) params.get("tenant");
        List<BriChannel> briChannels = briChannelService.getEnableChannelByChannel(ChannelEnum.DIDI.getName());
        for (BriChannel briChannel : briChannels) {
            DiDiConfig diDiConfig = (DiDiConfig) briChannelService.getChannelConfig(tenant, ChannelEnum.DIDI.getName(), new DiDiConfig());
            String fetchDate = (String) params.get("fetchDate");
            diDiOrderService.getDiDiOrderList(diDiConfig, fetchDate, tenant, briChannel.getId());
        }
        return null;
    }

    @RequestMapping(value = "/didiplat", method = RequestMethod.GET)
    public void didilat(String tenant, String tenantname, String userid, HttpServletResponse response) throws IOException {
        String tokenResultStr = diDiCompanyService.getPlatUrl(tenant, tenantname, userid);
        JSONObject tokenResult = new JSONObject(tokenResultStr);
        String authToken = "";
        if (0 == tokenResult.optInt("errno") && "SUCCESS".equals(tokenResult.optString("errmsg"))) {
            authToken = tokenResult.optJSONObject("data").optString("open_auth_token");
            int authStatus = tokenResult.optJSONObject("data").optInt("auth_status");
            if (0 == authStatus) {
                response.sendRedirect(authIndex + "?open_auth_token=" + authToken);
            } else {
                response.getWriter().write("已经在授权中或已经授权，请稍后再试！");
                response.getWriter().flush();
            }
        }
        response.getWriter().write("获取授权信息出错，请稍后再试！");
    }

    @RequestMapping(value = "/callback", method = RequestMethod.POST)
    public @ResponseBody
    Map ddCallBack(HttpServletRequest request) {
        DefaultMultipartHttpServletRequest multiReq = (DefaultMultipartHttpServletRequest) request;

        Map<String, String> params = new HashMap<>();
        params.put("type", multiReq.getParameter("type"));
        params.put("company_id", multiReq.getParameter("company_id"));
        params.put("out_company_id", multiReq.getParameter("out_company_id"));
        params.put("out_company_name", multiReq.getParameter("out_company_name"));
        params.put("out_member_id", multiReq.getParameter("out_member_id"));
        params.put("phone", multiReq.getParameter("phone"));
        params.put("auth_scope", multiReq.getParameter("auth_scope"));
        params.put("callback", multiReq.getParameter("callback"));
        params.put("client_id", multiReq.getParameter("client_id"));
        params.put("client_secret", multiReq.getParameter("client_secret"));
        return diDiCompanyService.ddCallBack(params);
    }

    @RequestMapping(value = "/callback1", method = RequestMethod.POST)
    public @ResponseBody
    Map ddCallBack1(HttpServletRequest request) {
        System.out.println("hello");

        return new HashMap();
    }

    @RequestMapping(value = "/isauth", method = RequestMethod.POST)
    public @ResponseBody
    boolean isAuth(@RequestBody Map params) {
        String tenant = params.get("tenant").toString();
        boolean result = diDiCompanyService.isAuthTenant(tenant);
        return result;
    }

    @RequestMapping(value = "/synUsers", method = RequestMethod.POST)
    @ResponseBody
    public BasicResult<Object> synUsers(@RequestBody Map params) {
        String tenant = params.get("tenant").toString();
        String phone = (String) params.get("phone");
        BriChannel briChannel = briChannelService.getEnableChannelByOpenType(tenant, ChannelEnum.DIDI.getName(), 1);
//        if (BriChannel.NEEDSYNCUSER == briChannel.getNeedSyncUser()) {
            diDiUserService.syncUsers4Open(tenant, phone);
            return BasicResult.success();
//        }
//        return BasicResult.fail("2001001", "该租户未配置同步用户");
    }

    @RequestMapping(value = "/query", method = RequestMethod.POST)
    @ResponseBody
    public com.alibaba.fastjson.JSONObject queryUsers(@RequestBody Map params) {
        String tenant = params.get("tenant").toString();
        String phone = (String) params.get("phone");
        return diDiUserService.querySingleUser(tenant, phone);
    }
}
